package com.fendaren.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fendaren.base.BaseInfoProperties;
import com.fendaren.controller.intercept.JWTCurrentUserInterceptor;
import com.fendaren.grace.result.GraceJSONResult;
import com.fendaren.grace.result.ResponseStatusEnum;
import com.fendaren.pojo.Admin;
import com.fendaren.pojo.bo.AdminBO;
import com.fendaren.pojo.vo.AdminVO;
import com.fendaren.service.AdminService;
import com.fendaren.util.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("admin")
@Slf4j
public class AdminController extends BaseInfoProperties {

    @Autowired
    private AdminService adminService;
    @Autowired
    private JWTUtils jWTUtils;

    @PostMapping("login")
    public GraceJSONResult login(@Valid @RequestBody AdminBO adminBO) throws JsonProcessingException {

        boolean isExist = adminService.adminLogin(adminBO);
        if (!isExist) {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.ADMIN_LOGIN_ERROR);
        }
        Admin admin = adminService.getAdminInfo(adminBO);
        String adminToken = jWTUtils.createJWTWithPrefix(new ObjectMapper().writeValueAsString(admin), TOKEN_ADMIN_PREFIX);

        return GraceJSONResult.ok(adminToken);
    }

    @GetMapping("info")
    public GraceJSONResult info() {

        Admin admin = JWTCurrentUserInterceptor.adminUser.get();
        AdminVO adminVO = new AdminVO();
        BeanUtils.copyProperties(admin, adminVO);
        return GraceJSONResult.ok(adminVO);
    }
}
